<template>

  <!-- 自定义对话框 -->
  <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="engineerinMessageCRUD"
      header="*情况"
      width="35%"
      :on-before-save-data="handleDialogSaveData"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      
      <t-form-item label="对接人" name="receiverId" :rules="[{ required: true, message: '请输入对接人' }]">
        <t-cascader
          v-model:value="formData.receiverId"
          :options="sendersTree"
          :keys="{ value: 'id', label: 'name' }"
          placeholder=""
          filterable
          clearable
        />
      </t-form-item>
      <t-form-item label="关联工地" name="engineeringId" :rules="[{ required: true, message: '请选择关联工地' }]">
        <t-select v-model:value="formData.engineeringId" clearable :filter="filterMethod" readonly placeholder="">
            <t-option v-for="_ in orderPersonList" :key="_.id" :value="_.id" :label="_.customerName">
              {{ _.customerName }}
              {{ propertyInfoList.find((item) => item.id === _.propertyName)?.name }} 
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
      </t-form-item>
      <t-form-item label="问题" name="problem" :rules="[{ required: true, message: '请输入问题' }]">
        <t-input v-model:value="formData.problem" placeholder="请输入问题" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="反馈" name="feedback" :rules="[{ required: true, message: '请输入反馈' }]">
        <t-input v-model:value="formData.feedback" placeholder="请输入反馈" clearable :readonly="readonly" />
      </t-form-item>
       <t-form-item label="类型" name="type" :rules="[{ required: true, message: '请选择类型' }]">
        <t-radio-group v-model:value="formData.type" clearable :readonly="readonly" placeholder="" :options="[
            {label:'在施',value:'1'},
            {label:'售后',value:'2'},
            ]">
        </t-radio-group>
      </t-form-item>

      <t-form-item label="图片/文件" name="imageUrl" >
        <upload2 v-model:files="formData.imageUrl" />
      </t-form-item>

      
    </custom-dialog>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { PropType, ref, useTemplateRef } from 'vue';
import { engineerinMessageCRUD } from '@/api/notice/engineering';
import Upload2 from '@/components/upload/index2.vue';
import CustomDialog from '@/components/custom/dialog/index.vue';
import { propertyManageCRUD } from '@/api/config/property';
import { engineeringListCRUD } from '@/api/project/engineering';
import listToTree from '@/utils/listToTree';
import { getSimpleDeptList } from '@/api/system/dept';
import { getSimpleUserList } from '@/api/system/user';

// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
      handleGetOrderPersonList();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 人员列表
const orderPersonList = ref([])
// 处理获取楼盘信息列表
const handleGetOrderPersonList = () => {
  const params = {
    pageSize: 99999,
    pageNo:1,
  };
  engineeringListCRUD.page(params)
    .then((data) => {
      orderPersonList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
interface userTreeData {
  id: string | number;       // 节点唯一标识（可能是用户ID或部门ID）
  deptId?: string | number;  // 部门ID（仅部门节点可能有）
  name: string;             // 节点显示名称（部门名或用户名）
  parentId: string | number; // 父节点ID（用于构建树形结构）
  children?: userTreeData[]; // 子节点（`listToTree` 可能会自动添加）
}
const sendersTree = ref([])
const handleGetUserTree = () => {
  Promise.all([getSimpleDeptList(),getSimpleUserList()])
  .then((res) => {
    const arr: userTreeData[] = []
    console.log(res,'pp');
    
    res[0].forEach((item: any) => {
      arr.push({
        id: `dept_${item.id}`,
        deptId:`dept_${item.id}`,
        name: item.name,
        parentId: item.parentId?`dept_${item.parentId}`:'',
      });
    });
    res[1].forEach((item: any) => {
      arr.push({
        id:item.id,
        name:item.nickname,
        parentId: item.deptId?`dept_${item.deptId}`:'',
      })
    })
    sendersTree.value = listToTree(arr, 'deptId').filter(item => item.id === 'dept_100')
  })
  .catch(() => {
    sendersTree.value = []
  })
}
handleGetUserTree()
// emits
const emits = defineEmits(['requestSuccess']);
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
 params.imageUrl = JSON.parse(params.imageUrl)
};

// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  console.log(params,'loh');
  
  const engineeringId = params.id
  customDialogRef.value.open(mode, { engineeringId: engineeringId, imageUrl:[] });
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  const hasWaitingFiles = params.imageUrl.some((item: any) => item.status === 'waiting');
  if (hasWaitingFiles) {
    MessagePlugin.warning('有文件待上传，请点击上传文件');
    return false;
  }
  if (params.engineeringId) {
    const selectedEngineering = orderPersonList.value.find(
      item => item.id === params.engineeringId
    );
    if (selectedEngineering) {
      params.orderId = selectedEngineering.orderId;
    }
  }
  return params;
};
// 订单信息过滤搜索 搜到地址
const filterMethod = (inputValue: string, option: any) => {
  // 根据 option.value 找到原始数据项
  const originalItem = orderPersonList.value.find(item => item.id === option.value);
  if (!originalItem) return false;
  
  // 创建搜索字符串（包含名称和地址）
  const searchString = `${originalItem.customerName} ${originalItem.address}`.toLowerCase();
  return searchString.includes(inputValue.toLowerCase());
};
defineExpose({
  handleOpenDialog,
});
</script>
